﻿using System;
using System.IO;

namespace YbxLibrary
{
    public class Logger
    {
        private static string logDirectory = AppDomain.CurrentDomain.BaseDirectory+"\\Logs";  // 日志存储目录
        private static string logFilePrefix = "log_";     // 日志文件前缀
        private static long maxLogFileSize = 30 * 1024 * 1024; // 30MB 文件大小限制
        private static string currentLogFileName;

        public static void Log(string message)
        {
            string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            IniFileUtils iniFile = new IniFileUtils(currentDirectory + "yb.ini");
            int  len = Convert.ToInt32(iniFile.ReadValue("log", "len"));

            try
            {
                string dateTime = DateTime.Now.ToString("yyyyMMdd");
                string logFileName = $"{logFilePrefix}{dateTime}.log";
                string logFilePath = Path.Combine(logDirectory, logFileName);

                if (currentLogFileName != logFilePath || ShouldCreateNewLogFile(logFilePath))
                {
                    currentLogFileName = logFilePath;
                }

                if (!Directory.Exists(logDirectory))
                {
                    Directory.CreateDirectory(logDirectory);
                }

                using (StreamWriter writer = new StreamWriter(logFilePath, true))
                {
                    writer.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message.Substring(0, message.Length<len ? message.Length-1 : len)}");
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine($"日志写入失败: {ex.Message}");
            }
        }

        private static bool ShouldCreateNewLogFile(string logFilePath)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(logFilePath);
                return fileInfo.Exists && fileInfo.Length > maxLogFileSize;
            }
            catch
            {
                return false;
            }
        }
    }
}
